// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-16

package arcade_follow_cancel

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/log"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib/authorizer"
)

// Logic
// 取消关注逻辑.
type Logic struct {
	auth     *authorizer.Authentication
	follow   *models.FollowArcade
	found    bool
	model    *models.Arcades
	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.auth = authorizer.New().Get(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)

	// 1. 事务处理.
	if err = db.Transaction(ctx,
		o.RunSelect,
		o.RunCompare,
		o.RunUpdate,
	); err != nil {
		return res.WithError(err)
	}

	// 2. 处理完成.
	return res.With(o.response.With(o.model, false))
}

func (o *Logic) RunSelect(ctx context.Context, sess *db.Session) (err error) {
	var has bool
	if o.model, has, err = services.NewArcadesService(sess).Dao.GetById(ctx, o.request.ArcadeId); err != nil {
		err = errs.ErrDatabaseQuery
		return
	} else if !has {
		err = errs.ErrArcadeNotFound
	}
	return
}

func (o *Logic) RunCompare(ctx context.Context, sess *db.Session) (err error) {
	var service = services.NewFollowArcadeService(sess)

	// 1. 读取历史.
	if o.follow, o.found, err = service.Dao.GetByMap(ctx, map[string]any{
		"arcade_id": o.request.ArcadeId,
		"user_id":   o.auth.UserId,
	}); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 删除关注.
	if o.found {
		if _, err = service.Dao.DeleteById(ctx, o.follow.Id); err != nil {
			err = errs.ErrDatabaseQuery
		}
	}
	return
}

func (o *Logic) RunUpdate(ctx context.Context, sess *db.Session) (err error) {
	// 1. 从未关注.
	if !o.found {
		return
	}

	// 2. 更新记数.
	var affects int64

	if affects, err = sess.Cols("follow_count").Decr("follow_count").Where("`id` = ?", o.request.ArcadeId).Update(models.Arcades{}); err != nil {
		err = errs.ErrDatabaseQuery
	} else {
		if affects > 0 {
			o.model.FollowCount--
		}
		log.Infofc(ctx, `update statistic: affect=%d`, affects)
	}
	return
}
